package web.dropwizard.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import domain.model.project.Project;
import domain.model.project.ProjectType;
import util.jackson.serializer.JacksonWriter;

import java.io.IOException;

/**
 * @author Gregory Boissinot
 */
public class ProjectSerializer extends JsonSerializer<Project> {

    private JacksonWriter jacksonWriter;

    public ProjectSerializer() {
        this.jacksonWriter = new JacksonWriter();
    }

    @Override
    public void serialize(Project project, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException, JsonProcessingException {
        jsonGenerator.writeStartObject();
        jacksonWriter.writeMandatoryFieldValue(jsonGenerator, "org", project.getProjectId().getOrganization());
        jacksonWriter.writeMandatoryFieldValue(jsonGenerator, "name", project.getProjectId().getName());
        jacksonWriter.writeMandatoryFieldValue(jsonGenerator, "status", project.getStatus().getLabel());

        jacksonWriter.writeOptionalFieldValue(jsonGenerator, "description", project.getDescription());
        jacksonWriter.writeOptionalFieldValue(jsonGenerator, "scm", project.getProjectSCM());

        final ProjectType projectType = project.getProjectType();
        if (!isNullProjectType(projectType)) {
            final String projectTypeName = projectType.getName();
            jacksonWriter.writeOptionalFieldValue(jsonGenerator, "type", projectTypeName);
            jacksonWriter.writeOptionalFieldValue(jsonGenerator, projectTypeName, projectType);
        }

        jsonGenerator.writeEndObject();
    }

    private boolean isNullProjectType(ProjectType projectType) {
        return (projectType == null);
    }

}
